<?php

namespace App\Http\Controllers\Home\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Home\Resume as ResumeModel;
use App\Models\Home\Position as PositionModel;
use App\Models\Home\Part as PartModel;
use PositionClass;
use FileSystem;
use Carbon\Carbon;
use Position;
use Resume;
use Deliver;
use Users;
use Part;
use Frame;
use Tools;
use Auth;
use Illuminate\Support\Facades\DB;

class ResumeController extends Controller
{
    protected $passField = [
        'name','country_code','phone','email','wechat','sex','birthday','nationality','living','education','experience','position','state','country','salary','coming','brief','attachment'
    ];
    protected $resume;
    protected $resume_out;

    public function __construct()
    {
        $this->resume = get_config_cache('resume');
        $this->resume_out = get_config_cache('resume_out');
    }

    public function self(Request $request)
    {
        $in = [];

        if (!Auth::user()->hasRole('admin') && Auth::user()->type==1){

            $user = Auth::user()->load('frame');

            $member = Frame::getMember($user->frame->id);

            $member[] = Auth::id();

            $member = array_merge($member,Part::getPartUser($member));

            $in = ['assign',$member];

        }else{

            $in = ['uid',[Auth::id()]];

        }

        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $opt = [];

        if (Auth::user()->type != 1){

            $opt['user_time'] = ['>',time()];

        }

        # 如果上级是管理组就拥有上级和兄弟查看权限
        $belong  = json_decode(Db::table('frame')->where(['uid'=>Auth::id()])->get(),true);

        if(@$belong[0]['level']==3 && @$belong[0]['belong']!=0 ){

            $borther = json_decode(Db::table('frame')->where(['belong'=>$belong[0]['belong']])->select('uid')->get(),true);

            foreach($borther as $k=>$v){
                $borther2[] = $v['uid'];
            }

            array_push($borther2,$belong[0]['belong']);

            if($borther2){
                $in = [
                    'assign',$borther2
                ];
            }

        }

        $opt['status'] = ['!=','-1'];

        $list = Resume::getList($page_info['skip'],$page_info['limit'],$opt,$in);

        $count = Resume::getCount($opt,$in);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        $resume_day = $this->resume;

        $resume_out_day = $this->resume_out;

        return view('Home.User.Resume.resume_self',compact('list','page','num','resume_day','resume_out_day'));
    }

    public function all(Request $request)
    {

        $in = [];
        $opt = [];
        $name_list = [];

        if ($name1 = $request->input('user1')){
            $name_list[] = $name1;
        }
        if ($name2 = $request->input('user2')){
            $name_list[] = $name2;
        }

        if (!empty($name_list)){
            $in = ['assign', $name_list];
        }
        if (!empty($request->name)){
            $opt['name'] = ['=',$request->name];
        }
        if (!empty($request->phone)){
            $opt['phone'] = ['like','%'.$request->phone.'%'];
        }

        $page = $request->input('page');

        $opt['status'] = ['!=','-1'];

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $list = Resume::getList($page_info['skip'],$page_info['limit'],$opt,$in);

        $count = Resume::getCount($opt);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        $user = Users::getUserList();

        $resume_day = $this->resume;

        $name  = $request->name;

        $phone = $request->phone;

        return view('Home.User.Resume.resume_all',compact('list','page','num','user','resume_day','name','phone','name1','name2'));
    }

    public function add(Request $request,PositionModel $obj=null){
        if($request->isMethod('post')){
            //验证
            $rules = [
                'name' => 'required|string',
                'country_code' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'phone' => ['required','string',function($attribute, $value, $fail){
                    $user = ResumeModel::where('phone',trim($value))->where('status',1)->first();
                    if ($user){
                        $fail(':attribute 已存在。');
                    }
                }],
                'email' => ['required','string',function($attribute, $value, $fail){
                    $user = ResumeModel::where('email',trim($value))->where('status',1)->first();
                    if ($user){
                        $fail(':attribute 已存在。');
                    }
                }],
                'wechat' => 'nullable|string',
                'sex' => 'required|integer',
                'birthday' => 'required|string',
                'nationality' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'living' => 'nullable|string',
                'education' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'experience' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'position' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'state' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'country' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'salary' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'coming' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'brief' => 'nullable|string',
                'shareTo' => 'required|integer',
            ];

            if ($obj){
                unset($rules['phone'][2]);
                unset($rules['email'][2]);
                unset($rules['file']);
                unset($rules['shareTo']);
            }else if(Auth::user()->type != 1){
                unset($rules['shareTo']);
            }

            $this->validate(request(), $rules,[],[
                'name' => '姓名',
                'country_code' => '国家区号',
                'phone' => '手机',
                'email' => '电子邮箱',
                'wechat' => '微信',
                'sex' => '性别',
                'birthday' => '出生年月',
                'nationality' => '国籍',
                'living' => '现居地',
                'education' => '学历',
                'experience' => '工作经验',
                'position' => '求职职位',
                'state' => '求职状态',
                'country' => '期待国家',
                'salary' => '期待月薪',
                'coming' => '到岗时间',
                'brief' => '一句话介绍',
                'shareTo' => '任务归属',
            ]);

            //数据库操作
            $data = [];

            $file_id = intval(request()->input('file_id'));
            if($file_id){
                $data['attachment'] = $file_id;
            }

            foreach ($request->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    if ($key == 'birthday'){
                        $val = Carbon::parse($val);
                    }
                    $data[$key] = $val;
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $data['assign'] = Auth::id();
                    $data['assign_time'] = strtotime('+ '.$this->resume.' day',time());
                    $data['share'] = 0;
                    break;
                case 2:
                    $data['assign'] = '';
                    $data['assign_time'] = '';
                    $data['share'] = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $data['assign'] = $assign;
                        $data['assign_time'] = strtotime('+ '.$this->resume.' day',time());
                        $data['share'] = 0;
                    }else{
                        $data['assign'] = '';
                        $data['assign_time'] = '';
                        $data['share'] = 1;
                    }
                    break;
                default:
                    $data['assign'] = '';
                    $data['assign_time'] = '';
                    $data['share'] = 1;
            }

            if ($obj){
                $data['assign'] = $obj->assign;
                $data['assign_time'] = strtotime('+ '.$this->resume.' day',time());
                $data['share'] = 0;
            }else{
                $data['uid'] = Auth::id();
                if (Auth::user()->type != 1){
                    $part = PartModel::where('create_uid',Auth::id())->first();
                    if ($part){
                        if ($part->assign){
                            $data['assign'] = $part->assign;
                        }else{
                            $data['assign'] = $part->uid;
                        }
                        $data['assign_time'] = strtotime('+ '.$this->resume.' day',time());
                        $data['share'] = 0;
                    }else{
                        $data['assign'] = '';
                        $data['assign_time'] = '';
                        $data['share'] = 1;
                    }

                    $data['user_time'] = strtotime('+ '.$this->resume_out.' day',time());
                }
            }

            $resume = ResumeModel::create($data);

            if ($resume && $obj){
                $deliver_data['resume_id'] = $resume->id;
                $deliver_data['position_id'] = $obj->id;
                $resume->deliver()->create($deliver_data);
            }

            return ['code'=>1];
            //返回结果
        }

        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        $position_class = PositionClass::getTreeList();
        $country = config('base.country');
        $education = config('base.education');
        $working_time = config('base.working_time');
        $working_state = config('base.working_state');
        $working_salary = config('base.working_salary');
        $arrival_time = config('base.arrival_time');

        $resume_day = $this->resume;
        $resume_out_day = $this->resume_out;

        return view('Home.User.Resume.resume_add',compact('frame','obj','position_class','country','education','working_time','working_state','working_salary','arrival_time','resume_day','resume_out_day'));
    }

    public function edit(ResumeModel $obj){
        if(request() ->isMethod('post')){
            //验证
            $rules = [
                'name' => 'required|string',
                'country_code' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'phone' => ['required','string',function($attribute, $value, $fail) use($obj){
                    if ($obj->phone != trim($value)){
                        $user = ResumeModel::where('phone',trim($value))->where('status',1)->first();
                        if ($user){
                            $fail(':attribute 已存在。');
                        }
                    }
                }],
                'email' => ['required','string',function($attribute, $value, $fail) use($obj){
                    if ($obj->email != trim($value)) {
                        $user = ResumeModel::where('email', trim($value))->where('status', 1)->first();
                        if ($user) {
                            $fail(':attribute 已存在。');
                        }
                    }
                }],
                'wechat' => 'nullable|string',
                'sex' => 'required|integer',
                'birthday' => 'required|string',
                'nationality' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'living' => 'nullable|string',
                'education' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'experience' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'position' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'state' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'country' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'salary' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'coming' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'brief' => 'nullable|string',
                'file_id' => 'required',
                'shareTo' => 'required|integer',
            ];

            if (Auth::user()->type == 1){
                if (($obj->share || $obj->assign == Auth::id()) && $obj->uid!=Auth::id() && !Auth::user()->hasRole('admin')){
                    foreach ($rules as $k => $v){
                        if ($k != 'shareTo'){
                            unset($rules[$k]);
                        }
                    }
                }
            }else{
                if ($obj->uid==Auth::id()){
                    unset($rules['shareTo']);
                }
            }

            $this->validate(request(), $rules,[],[
                'name' => '姓名',
                'country_code' => '国家区号',
                'phone' => '手机',
                'email' => '电子邮箱',
                'wechat' => '微信',
                'sex' => '性别',
                'birthday' => '出生年月',
                'nationality' => '国籍',
                'living' => '现居地',
                'education' => '学历',
                'experience' => '工作经验',
                'position' => '求职职位',
                'state' => '求职状态',
                'country' => '期待国家',
                'salary' => '期待月薪',
                'coming' => '到岗时间',
                'brief' => '一句话介绍',
                'file_id' => '附件简历',
                'shareTo' => '任务归属',
            ]);

            //数据库操作
            foreach (request()->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    if ($key == 'birthday'){
                        $val = Carbon::parse($val);
                    }
                    $obj->$key = $val;
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $obj->assign = Auth::id();
                    $obj->assign_time = strtotime('+ '.$this->resume.' day',time());
                    $obj->share = 0;
                    break;
                case 2:
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $obj->assign = $assign;
                        $obj->assign_time = strtotime('+ '.$this->resume.' day',time());
                        $obj->share = 0;
                    }else{
                        $obj->assign = '';
                        $obj->assign_time = '';
                        $obj->share = 1;
                    }
                    break;
                default:
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
            }

            if (Auth::user()->type != 1){
                $part = PartModel::where('create_uid',Auth::id())->first();
                if ($part){
                    if ($part->assign){
                        $obj->assign = $part->assign;
                    }else{
                        $obj->assign = $part->uid;
                    }
                    $obj->assign_time = strtotime('+ '.$this->resume.' day',time());
                    $obj->share = 0;
                }else{
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
                }
            }

            $file_id = intval(request()->input('file_id'));
            if($file_id){
                $obj->attachment = $file_id;
            }

            $res = $obj->save();
            //返回结果
            return ['code'=>1];
        }

        $obj = Tools::checkDown($obj);

        $obj->load(['user','file','assign_user']);

        $obj = Resume::SetAssign($obj);

        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        if ($obj->assign){
            if ($obj->assign == Auth::id()){
                $obj->shareTo = 1;
            }else{
                $obj->shareTo = 3;
            }
        }else{
            $obj->shareTo = 2;
        }

        $position_class = PositionClass::getTreeList();
        $country = config('base.country');
        $education = config('base.education');
        $working_time = config('base.working_time');
        $working_state = config('base.working_state');
        $working_salary = config('base.working_salary');
        $arrival_time = config('base.arrival_time');

        $resume_day = $this->resume;
        $resume_out_day = $this->resume_out;

        $obj->birthday = date('Y-m',strtotime($obj->birthday));

        return view('Home.User.Resume.resume_edit',compact('obj','frame','position_class','country','education','working_time','working_state','working_salary','arrival_time','resume_day','resume_out_day'));
    }

    public function resume_push(ResumeModel $obj){

        if(request() ->isMethod('post')){
            //验证
            $this->validate(request(), [
                'id_list' => 'required',
            ],[
                'required' => '必选'
            ],[
                'id_list' => '职位数据'
            ]);

            //数据库操作

            $id_list = request()->post('id_list');

            $data = [];

            foreach ($id_list as $k => $v){
                $data[$k]['position_id'] = $v;
                $data[$k]['uid'] = Auth::id();
                $data[$k]['status'] = 1;
                $data[$k]['assign']= Db::table('position')->where('id',$v)->value('assign');
                # 增加 跟进记录
                $data_schedule[$k]=[
                    'uid'=>Auth::id(),
                    'assign'=>$data[$k]['assign'],
                    'result'=>2,
                    'created_at'=>date('Y-m-d H:i:s',time()),
                    'updated_at'=>date('Y-m-d H:i:s',time()),
                ];
            }
            
            $res = $obj->deliver()->createMany($data);


            foreach($res->toArray() as $k=>$v){
                $data_schedule[$k]['deliver_id'] = $v['id'];
            }

            $obj->create_deliver_schedule($data_schedule);

            return ['code'=>1];
        }

        $in = [];

        $opt['state'] = 1;

        if (!Auth::user()->hasRole('admin') && Auth::user()->type==1){

            $user = Auth::user()->load('frame');

//            $member = Frame::getMember($user->frame->id);

            $member[] = Auth::id();

            $in = ['assign',$member];

        }else{

            $part = PartModel::where('create_uid',Auth::id())->first();

            if ($part && $part->assign && $part->share != 1){

                $in = ['assign',[$part->assign]];

            }else{

                $in = ['assign',[Auth::id()]];
            }

        }

        # 如果上级是管理组就拥有上级和兄弟查看权限
        $belong  = json_decode(Db::table('frame')->where(['uid'=>Auth::id()])->get(),true);

        if(@$belong[0]['level']==3 && @$belong[0]['belong']!=0 ){

            $borther = json_decode(Db::table('frame')->where(['belong'=>$belong[0]['belong']])->select('uid')->get(),true);

            foreach($borther as $k=>$v){
                $borther2[] = $v['uid'];
            }

            array_push($borther2,$belong[0]['belong']);

            if($borther2){
                $in = [
                    'assign',$borther2
                ];
            }

        }


        $list = Position::getList(true,true,$opt,$in,false,true,true,true,$obj->id);

        return view('Home.User.Resume.resume_push',compact('list','obj'));
    }

    public function resume_position(ResumeModel $obj,Request $request){

        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $opt = ['resume_id'=>$obj->id];

        $list = Deliver::getList($page_info['skip'],$page_info['limit'],$opt,'position');

        $count = Deliver::getCount($opt);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        return view('Home.User.Resume.resume_position',compact('list','obj','page','num'));
    }

    public function download(ResumeModel $obj){

        $obj = Tools::checkDown($obj);

        if ($obj->display){

            $fid = $obj->attachment;

            $res = FileSystem::downloadFile($fid,true);

            return response()->download($res['path'],$res['name']);

        }

    }

    public function buy(ResumeModel $obj){

        $user = Auth::user();

        $rerurn = ['code'=>0,'msg'=>'下载点不足'];

        if (intval($user->download-1) >= 0){

            $user->download = intval($user->download-1);

            $obj->download_log()->create(['uid'=>Auth::id(),'cid'=>$obj->id,'type'=>2]);

            $user->save();

            $rerurn = ['code'=>1,'msg'=>'OK'];
        }

        return $rerurn;

    }
    /*删除简历*/
    public function position_del(ResumeModel $obj){
        if(Auth::user()->hasAnyRole(['admin']) || Auth::id()==$obj->uid){

            $obj->status = '-1';

            $res = $obj->save();

            if ($res){

                $rerurn = ['code'=>1,'msg'=>'OK'];

            }else{

                $rerurn = ['code'=>0,'msg'=>'服务器错误'];
            }
        }else{

            $rerurn = ['code'=>0,'msg'=>'没有权限'];
        }

        return $rerurn;
    }
    /*删除已推荐简历*/
    public function del(Request $request)
    {

            $id = $request->obj?$request->obj:0;

            $res = Db::table('deliver')->where('id',$id)->delete();

            if ($res){

                $rerurn = ['code'=>1,'msg'=>'OK'];

            }else{

                $rerurn = ['code'=>0,'msg'=>'服务器错误'];
            }

        return $rerurn;
    }

}